package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.aiassistant.domain.entity.AiOpportunityEntity;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.model.PaasFormDataEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.pojo.MultiUnitPricePoJo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.EnableApiCallBack;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.ApiCallBackEnum;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.MultiUnitConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.OpportunityDao;
import com.xbongbong.saas.domain.entity.OpportunityProductEntity;
import com.xbongbong.saas.domain.entity.competitor.CompetitorEntity;
import com.xbongbong.saas.domain.entity.ext.OpportunityEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.enums.OperatePageEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RelativeProductEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.UpdateDataTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CompetitorEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.product.OpportunityProductEnum;
import com.xbongbong.saas.help.CompetitorHelp;
import com.xbongbong.saas.help.ExplainHelp;
import com.xbongbong.saas.help.SaasFormHelp;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.CompetitorModel;
import com.xbongbong.saas.model.OpportunityModel;
import com.xbongbong.saas.model.OpportunityProductModel;
import com.xbongbong.saas.model.OpportunitySubDataModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductUnitPriceModel;
import com.xbongbong.saas.model.SpecificationModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author long.rao
 * @version v1.0
 * @date 2019/1/22 16:56
 * @since v1.0
 */
@Service("opportunityModel")
public class OpportunityModelImpl implements OpportunityModel {
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private OpportunityDao opportunityDao;
    @Resource
    private PaasFormDataEsModel paasFormDataEsModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private OpportunitySubDataModel opportunitySubDataModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private ExplainHelp explainHelp;
    @Resource
    private ShowFormatHelp showFormatHelp;
    @Resource
    private SpecificationModel specificationModel;
    @Resource
    private SaasFormHelp saasFormHelp;
    @Resource
    private ProductUnitPriceModel productUnitPriceModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private OpportunityProductModel opportunityProductModel;
    @Resource
    private CompetitorHelp competitorHelp;

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.SALES_OPPORTUNITY, operateTypeEnum = OperateTypeEnum.NEW)
    public Integer insert(OpportunityEntityExt entity) throws XbbException {
        //TODO  先进行数据库的插入动作
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_OPPORTUNITY_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = opportunityDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_OPPORTUNITY);
        paasEsModel.insert(insertDTO);
        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_OPPORTUNITY_SUB);
        return success;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.SALES_OPPORTUNITY, operateTypeEnum = OperateTypeEnum.EDIT)
    public Integer update(OpportunityEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_OPPORTUNITY_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = opportunityDao.update(entity);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_OPPORTUNITY_SUB);
        if (Objects.equals(1, success) || Objects.equals(1, updateSub)) {
            // 更新时间
            success = opportunityDao.updateTime(now + 1, entity.getId(), entity.getCorpid());
            // 更新es
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity, false);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_OPPORTUNITY);
            insertDTO.getSource().remove("creatorId");
            paasEsModel.update(insertDTO);

        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }
        return success;
    }

    @Override
    public List<OpportunityEntityExt> findEntitys(Map<String, Object> param) {
        List<OpportunityEntityExt> entitys = opportunityDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_OPPORTUNITY_SUB);
        }
        return entitys;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return opportunityDao.getEntitysCount(param);
    }

    @Override
    public OpportunityEntityExt getByKey(Long key, String corpid) {
        OpportunityEntityExt entityExt = opportunityDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(entityExt), IndexTypeEnum.IDX_SAAS_OPPORTUNITY_SUB);
        return entityExt;
    }

    @Override
    public List<OpportunityEntityExt> getOpportunityByEstimateEndTime(String corpid, Long startEstimateEndTime, Long endEstimateEndTime) {
        List<OpportunityEntityExt> entityExts = opportunityDao.getOpportunityByEstimateEndTime(corpid, startEstimateEndTime, endEstimateEndTime);
        paasFormSubDataModel.findSubEntity(corpid, entityExts, IndexTypeEnum.IDX_SAAS_OPPORTUNITY_SUB);
        return entityExts;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.SALES_OPPORTUNITY, operateTypeEnum = OperateTypeEnum.DELETE, isBatch = true)
    public Integer deleteBatch(List<Long> idIn, String corpid) throws XbbException {

        return deleteBatch(idIn, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.SALES_OPPORTUNITY, operateTypeEnum = OperateTypeEnum.DELETE, isBatch = true)
    public Integer deleteBatch(List<Long> idIn, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        if (CollectionsUtil.isEmpty(idIn)) {
            return 0;
        }
        Integer integer = opportunityDao.deleteBatch(idIn, corpid);
        paasEsModel.deleteBatch(idIn, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_OPPORTUNITY, refreshPolicy);
        paasFormSubDataModel.deleteBatchByDataId(idIn, corpid, IndexTypeEnum.IDX_SAAS_OPPORTUNITY_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.SALES_OPPORTUNITY, operateTypeEnum = OperateTypeEnum.DELETE)
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_OPPORTUNITY);
        paasEsModel.delete(deleteDTO);
        Integer integer = opportunityDao.deleteByKey(key, corpid);
        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_OPPORTUNITY_SUB);
        return integer;
    }

    @Override
    public OpportunityEntityExt getLatestEntityByCustomerId(String corpid, Long customerId) throws XbbException {
        OpportunityEntityExt opportunity = null;
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(SalesOpportunityEnum.getEsAttr4Keyword(SalesOpportunityEnum.CUSTOMER_NAME), customerId));
        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_OPPORTUNITY.getType()));
        sourceBuilder.query(boolQueryBuilder);
        sourceBuilder.sort(SalesOpportunityEnum.ADD_TIME.getAttr(), SortOrder.DESC);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_OPPORTUNITY.getIndex());
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 0, 1);
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<OpportunityEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, OpportunityEntityExt.class);
        List<OpportunityEntityExt> list = esEntities.getContent();
        if (!list.isEmpty()) {
            opportunity = list.get(0);
        }
        return opportunity;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.SALES_OPPORTUNITY, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer  = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer =opportunityDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_OPPORTUNITY);
        }
        // todo
        if (!subList.isEmpty()) {
            opportunitySubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.SALES_OPPORTUNITY, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer  = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer =opportunityDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_OPPORTUNITY, refreshPolicy);
        }
        // todo
        if (!subList.isEmpty()) {
            opportunitySubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, boolean needThrow) throws XbbException {
        Integer integer = opportunityDao.updateBatch(updateList, corpid);
        paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_OPPORTUNITY, needThrow);
        return integer;
    }

    @Override
    public Integer updateBatch4Script(List<UpdateDataEntity> updateList, boolean async) throws XbbException {
        StandardizeDataUtil.standardizeList(updateList);
        Integer integer = opportunityDao.updateBatch4Script(updateList);
        if (async) {
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_OPPORTUNITY, WriteRequest.RefreshPolicy.NONE);
        } else {
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_OPPORTUNITY);
        }
        return integer;
    }

    @Override
    public Integer updateBatch4Sync(List<UpdateDataEntity> updateList, String corpid) throws XbbException {
        StandardizeDataUtil.standardizeList(updateList);
        Integer integer = opportunityDao.updateBatch4Sync(updateList, corpid);
        paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_OPPORTUNITY);
        return integer;
    }

    /**
     * 数据还原
     * @param dataIdList
     * @param corpid
     * @param del
     * @throws XbbException
     */
    @Override
    public Integer restoreBatch(List<Long> dataIdList, String corpid, Integer del) throws XbbException {
        Integer count = opportunityDao.restoreBatch(dataIdList, corpid, del);
        updateBatchDel(dataIdList, corpid, del);
        paasFormSubDataModel.restoreBatch(dataIdList, corpid,IndexTypeEnum.IDX_SAAS_OPPORTUNITY_SUB);
        return count;
    }

    @Override
    public List<AiOpportunityEntity> getOpportunityList4Ai(String corpid, List<Long> idIn) {
        return opportunityDao.getOpportunityList4Ai(corpid, idIn);
    }

    private void updateBatchDel(List<Long> dataIdList, String corpid, Integer del) throws XbbException{
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("del", del);
        map.put("updateTime",DateTimeUtil.getInt());
        paasFormDataEsModel.updateBatch(dataIdList, corpid, map, IndexTypeEnum.IDX_SAAS_OPPORTUNITY);
    }

    @Override
    public List<OpportunityEntityExt> findEntitysWithoutSub(Map<String, Object> param) {
        return opportunityDao.findEntitys(param);
    }

    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        String corpid = formatExplainDTO.getCorpid();
        Integer fromCopy = 0;
        if (Objects.nonNull(formatExplainDTO.getFromCopy())) {
            fromCopy = formatExplainDTO.getFromCopy() ? 1 : 0;
        }
        if (Objects.nonNull(formatExplainDTO.getSaasSpecialParamPojo())) {
            fromCopy = formatExplainDTO.getSaasSpecialParamPojo().getFromCopy();
        }
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            String attr = fieldAttrEntity.getAttr();
            if (Objects.equals(attr, SalesOpportunityEnum.CUSTOMER_NAME.getAttr())) {
                fieldAttrEntity.setEditable(0);
            } else if (Objects.equals(attr, SalesOpportunityEnum.PRODUCTS.getAttr())) {
                explainHelp.formatSelectProductExplains(fieldAttrEntity, XbbRefTypeEnum.SALES_OPPORTUNITY, corpid, OperatePageEnum.NEW.getCode(), false);
            } else if (Objects.equals(attr, SalesOpportunityEnum.SALE_STAGE.getAttr()) && !Objects.equals(fromCopy, BasicConstant.ONE)) {
                fieldAttrEntity.setEditable(BasicConstant.ZERO);
                fieldAttrEntity.setMemo(I18nMessageUtil.getMessage(I18nStringConstant.CHANGE_SALES_STAGE_MEMO));
            } else if (Objects.equals(attr, SalesOpportunityEnum.WASTAGE.getAttr()) && !Objects.equals(fromCopy, BasicConstant.ONE)) {
                fieldAttrEntity.setEditable(BasicConstant.ZERO);
            } else if (Objects.equals(attr, SalesOpportunityEnum.COST.getAttr())
                    || Objects.equals(attr, SalesOpportunityEnum.GROSS_PROFIT.getAttr())
                    || Objects.equals(attr, SalesOpportunityEnum.GROSS_PROFIT_RATE.getAttr())) {
                fieldAttrEntity.setUnableEditMemo(I18nMessageUtil.getMessage(StringConstant.AUTO_GEN_FIELD));
            }
        }
    }

    /**
     * 编辑时将获取数据格式化
     *
     * @param formDataUpdateGetDTO saas编辑数据
     * @param result 要返回的jsonObject
     * @throws XbbException 业务异常
     * @author long.rao
     * @date 2019-01-23 10:18
     */
    @Override
    public void formatData(SaasAnalysisDataDTO formDataUpdateGetDTO, JSONObject result) throws XbbException {
        // 格式化关联客户字段
        showFormatHelp.formatLinkBusiness4ShowBySource(result, SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), SalesOpportunityEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), SalesOpportunityEnum.CUSTOMER_NAME.getFieldType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), formDataUpdateGetDTO.getCorpid());
        // 格式化关联联系人字段
        showFormatHelp.formatLinkBusiness4Show(result, SalesOpportunityEnum.CONTACT_NAME.getAttr(), SalesOpportunityEnum.CONTACT_NAME_LINK_TEXT.getAttr(), SalesOpportunityEnum.CONTACT_NAME.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, SalesOpportunityEnum.DECISION_MAKER.getAttr(), SalesOpportunityEnum.DECISION_MAKER_ID_LINK_TEXT.getAttr(), SalesOpportunityEnum.DECISION_MAKER.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, SalesOpportunityEnum.LINK_COMPETITOR.getAttr(), SalesOpportunityEnum.LINK_COMPETITOR_LINK_TEXT.getAttr(), SalesOpportunityEnum.LINK_COMPETITOR.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, SalesOpportunityEnum.WIN_COMPETITOR.getAttr(), SalesOpportunityEnum.WIN_COMPETITOR_LINK_TEXT.getAttr(), SalesOpportunityEnum.WIN_COMPETITOR.getFieldType());

        // 格式化关联产品
//        formatProduct4Show(result, formDataUpdateGetDTO);
//        // 解析竞争对手两个字段
//        competitorHelp.analysisCompetior(formDataUpdateGetDTO.getCorpid(),result);
    }

    @Override
    public void getProductList(String corpid, List<OpportunityProductEntity> opportunityProductEntityList, JSONArray productArray, Map<Long, ProductEntityExt> productMap) throws XbbException {
        // 产品排序
        Integer sort = 0;
        for (int i = 0; i < productArray.size(); i++) {
            JSONObject productJsonObject = productArray.getJSONObject(i);
            sort++;
            // 页面传入的产品id
            Long pageProductId = FastJsonHelper.getLongOrDefaultFromFormData(productJsonObject, StringConstant.SAAS_LINK_BUSINESS_ID, 0L);
            // 获取前端返回的产品成本
            Double cost = StringUtil.toDouble(productJsonObject.getString("estimateCost"), 0D);
            // 产品数量
            Double productNum = getDoubleOrDefaultFromFormData(productJsonObject, RelativeProductEnum.NUM.getSaasAttr(), 0D);
            // 售价
            Double salePrice = getDoubleOrDefaultFromFormData(productJsonObject, RelativeProductEnum.SALE_PRODUCT_PRICE.getSaasAttr(), 0D);
            // 折扣：默认为100%
            Double discount = getDoubleOrDefaultFromFormData(productJsonObject, RelativeProductEnum.SALE_DISCOUNT.getSaasAttr(), 0D);
            if (productMap.containsKey(pageProductId)) {
                ProductEntityExt product = productMap.get(pageProductId);
                JSONObject productObject = product.getData();
                String productName = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.NAME.getAttr(), "");
                String specification = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                specification = specificationModel.joinSpecification(specification);
                String unit = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.UNIT.getAttr(), "");
                String productNo = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.PRODUCT_NO.getAttr(), "");
                Double price = getDoubleOrDefaultFromFormData(productObject, ProductEnum.PRICE.getSaasAttr(), 0D);
                OpportunityProductEntity opportunityProduct = new OpportunityProductEntity();
                opportunityProduct.setProductUnit(unit);
                opportunityProduct.setCorpid(corpid);
                opportunityProduct.setProductId(pageProductId);
                opportunityProduct.setProductNum(productNum);
                opportunityProduct.setProductNo(productNo);
                opportunityProduct.setPrice(salePrice);
                opportunityProduct.setProductName(productName);
                opportunityProduct.setSpecification(specification);
                opportunityProduct.setDiscount(discount);
                opportunityProduct.setCost(cost);
                opportunityProduct.setSort(sort);
                /*JSONObject jsonObject = new JSONObject();
                jsonObject.put(OpportunityProductEnum.PRODUCT.getAttr(), pageProductId);
                jsonObject.put(OpportunityProductEnum.UNIT.getAttr(), unit);
                jsonObject.put(OpportunityProductEnum.PRICE.getAttr(), price);
                jsonObject.put(OpportunityProductEnum.SELL_TOTAL.getAttr(), salePrice * productNum);
                jsonObject.put(OpportunityProductEnum.NUM.getAttr(), productNum);
                jsonObject.put(OpportunityProductEnum.DISCOUNT.getAttr(), discount);
                jsonObject.put(OpportunityProductEnum.SELLING_PRICE.getAttr(), salePrice);
                jsonObject.put(OpportunityProductEnum.MEMO.getAttr(), "");
                opportunityProduct.setData(jsonObject);*/
                opportunityProductEntityList.add(opportunityProduct);
            }
        }
    }

    @Override
    public void formatProduct4Show2(Long dataId, String corpid, JSONObject data, UpdateDataTypeEnum updateDataTypeEnum) throws XbbException {
        // 获取关联产品
        List<OpportunityProductEntity> opportunityProductEntityList = new ArrayList<>();
        if (Objects.isNull(dataId) || Objects.equals(dataId, 0L)) {
            if (data.get(SalesOpportunityEnum.PRODUCTS.getAttr()) instanceof JSONObject) {
                JSONArray productArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, SalesOpportunityEnum.PRODUCTS.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
                Map<Long, ProductEntityExt> productMap = productModel.getProductMap(corpid, productArr);
                getProductList(corpid, opportunityProductEntityList, productArr, productMap);
            } else {
                JSONArray jsonArray = data.getJSONArray(SalesOpportunityEnum.PRODUCTS.getAttr());
                if (Objects.nonNull(jsonArray)) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        OpportunityProductEntity contractProductEntity = new OpportunityProductEntity();
                        contractProductEntity.setCorpid(corpid);
                        Long subProductId = FastJsonHelper.getLongFromFormData(jsonObject, BusinessConstant.PRODUCT_SUB_ID);
                        if (Objects.nonNull(subProductId)) {
                            contractProductEntity.setId(subProductId);
                        }
                        contractProductEntity.setProductId(jsonObject.getLong(SelectProductEnum.PRODUCT.getAttr()));
                        // 多单位
                        if (Objects.equals(1,jsonObject.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr()))) {
                            JSONArray unitRate = jsonObject.getJSONArray(ProductConstant.TRANSFORM_UNIT_RATE);
                            Long businessUnit = jsonObject.getLongValue(SelectProductEnum.UNIT.getAttr());
                            Double productNUm = jsonObject.getDoubleValue(SelectProductEnum.NUM.getAttr());
                            for (int j = 0; j < unitRate.size(); j++) {
                                JSONObject unitJson = unitRate.getJSONObject(j);
                                if (Objects.equals(businessUnit, unitJson.getLongValue(MultiUnitConstant.VALUE))) {
                                    contractProductEntity.setRate(unitJson.getDoubleValue(MultiUnitConstant.RATE));
                                }
                            }
                            contractProductEntity.setBusinessUnit(businessUnit);
                            contractProductEntity.setProductNum(productNUm);
                        }
                        contractProductEntity.setData(jsonObject);
                        opportunityProductEntityList.add(contractProductEntity);
                    }
                }
            }
        } else {
            opportunityProductEntityList = opportunityProductModel.getProductsByOppId(dataId, corpid, Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.APPROVE_FAILED.getDel()));
        }
        List<Long> productIdList = new ArrayList<>();
        opportunityProductEntityList.forEach(item->{
            productIdList.add(item.getProductId());
        });
        Map<Long, ProductEntityExt> productMap = productModel.getProductMapByIds(corpid, productIdList, DelEnum.NORMAL.getDel(), Arrays.asList(StringConstant.SAAS_LINK_BUSINESS_ID,ProductEnum.getAttrConnectData(ProductEnum.STOCK), ProductEnum.getEsAttr4Keyword(ProductEnum.NAME), ProductEnum.getAttrConnectData(ProductEnum.ONLINE), ProductEnum.getAttrConnectData(ProductEnum.ENABLE_MULTI_UNIT)));
        Set<Long> multiUnitProductIds = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        productMap.forEach((key,value)->{
            if (Objects.equals(value.getData().getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr()), 1)) {
                multiUnitProductIds.add(key);
            }
        });
        Map<Long, List<MultiUnitPricePoJo>> priceMap = productUnitPriceModel.getPriceMapByProductIdSet(corpid, multiUnitProductIds);
        JSONArray productArray = new JSONArray();
        Iterator iterator = opportunityProductEntityList.iterator();
        // fix:修复下架多个产品后也只显示一个，将hashset改为arraylist
        List<String> offlinedProducts = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        while (iterator.hasNext()){
            OpportunityProductEntity opportunityProductEntity = (OpportunityProductEntity)iterator.next();
            JSONObject oppProductData = opportunityProductEntity.getData();
            Long productId = -1L;
            if (Objects.nonNull(oppProductData)){
                productId = oppProductData.getLong(OpportunityProductEnum.PRODUCT.getAttr());
            } else {
                productId = opportunityProductEntity.getProductId();
            }
            ProductEntityExt productEntityExt = productMap.get(productId);
            if (Objects.isNull(productEntityExt)) {
                continue;
            }
            if (Objects.nonNull(priceMap.get(productId))) {
                opportunityProductEntity.setProductPriceArr(JSONArray.parseArray(JSONArray.toJSONString(priceMap.get(productId))));
            }
            JSONObject productData = productEntityExt.getData();
            if(Objects.equals(updateDataTypeEnum,UpdateDataTypeEnum.COPY)){
                // 下架产品剔除掉
                Integer online = productData.getInteger(ProductEnum.ONLINE.getAttr());
                String name = productData.getString(ProductEnum.NAME.getAttr());
                if (!Objects.equals(1,online)){
                    offlinedProducts.add(name);
                    continue;
                }
            }
            JSONObject json = formatSingleProduct(opportunityProductEntity);
            if (updateDataTypeEnum.isUpdate()){
                json.put(BusinessConstant.PRODUCT_SUB_ID,opportunityProductEntity.getId());
                if (Objects.isNull(opportunityProductEntity.getId())) {
                    json.put(BusinessConstant.PRODUCT_SUB_ID,0);
                }
            }else {
                json.put(BusinessConstant.PRODUCT_SUB_ID,0);
            }
            if (updateDataTypeEnum.isLinkAdd()){
                json.put(SelectProductEnum.UNIT.getAttr(), saasFormHelp.formatUnit(corpid,opportunityProductEntity.getProductUnit()));
                json.put(BusinessConstant.RELY_PRODUCT_SUB_ID, opportunityProductEntity.getId());
            }
            productArray.add(json);
        }
        data.put(SalesOpportunityEnum.PRODUCTS.getAttr(),productArray);
        data.put(BasicConstant.OFF_LINED_PRODUCTS,offlinedProducts);
    }

    @Override
    public JSONObject formatSingleProduct(OpportunityProductEntity opportunityProductEntity) {
        JSONObject json = opportunityProductEntity.getData();
        showFormatHelp.approvalSetBusinessUnit(json, opportunityProductEntity);
        if (Objects.isNull(json) || json.isEmpty()){
            json = new JSONObject();
            for (OpportunityProductEnum opportunityProductEnum : OpportunityProductEnum.values()){
                String attr = opportunityProductEnum.getAttr();
                switch (opportunityProductEnum){
                    case PRODUCT:
                        json.put(attr,opportunityProductEntity.getProductId());
                        break;
                    case DISCOUNT:
                        json.put(attr,opportunityProductEntity.getDiscount());
                        break;
                    case SELLING_PRICE:
                        json.put(attr,opportunityProductEntity.getPrice());
                        break;
                    case NUM:
                        json.put(attr,opportunityProductEntity.getProductNum());
                        break;
                    case MEMO:
                        json.put(attr,opportunityProductEntity.getMemo());
                        break;
                    case PRICE:
                        json.put(attr,opportunityProductEntity.getHistoricalPrice());
                        break;
                    case UNIT:
                        json.put(attr, opportunityProductEntity.getProductUnit());
                        break;
                    case SELL_TOTAL:
                        json.put(attr,opportunityProductEntity.getPrice() * opportunityProductEntity.getDiscount() * opportunityProductEntity.getProductNum() * 0.01);
                        break;
                    default:
                        break;
                }
            }
        }
        if (Objects.nonNull(opportunityProductEntity.getProductPriceArr())) {
            json.put(ProductConstant.PRODUCT_PRICE, opportunityProductEntity.getProductPriceArr());
        }
        return json;
    }

    @Override
    public Integer updateTime(Long id,String corpid) throws XbbException {
        long now = DateUtil.getInt();
        // 更新时间
        Integer success = opportunityDao.updateTime(now, id, corpid);
        // 更新es
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        paasFormDataEntity.setId(id);
        paasFormDataEntity.setDataId(id);
        paasFormDataEntity.setCorpid(corpid);
        paasFormDataEntity.setUpdateTime(now);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_OPPORTUNITY);
        insertDTO.getSource().remove("creatorId");
        paasEsModel.update(insertDTO);
        return success;
    }

    @Override
    public <T> List<T> getOpportunityListByLinkId(String corpid, Long linkId, SalesOpportunityEnum salesOpportunityEnum, Class<T> clazz) throws XbbException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(SalesOpportunityEnum.getEsAttr4Keyword(salesOpportunityEnum), linkId));
        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_OPPORTUNITY.getType()));
        sourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_OPPORTUNITY.getIndex());
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 0, PaasConstant.ES_MAX_PAGE_SIZE);
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<T> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, clazz);
        return esEntities.getContent();
    }

    @Override
    public void jsonsetNoSubById(String corpid, Long id, Map<String, Object> map) throws XbbException {
        StandardizeDataUtil.standardizeMap(map);
        Map<String,Object> map2 = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String,Object> updateDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        JSONObject jsonObject = new JSONObject();
        Long now = DateTimeUtil.getInt();
        for (Map.Entry<String,Object> entry : map.entrySet()){
            String key = entry.getKey();
            map2.put("$."+key,entry.getValue());
            jsonObject.put(key,entry.getValue());
        }
        updateDataMap.put("data", jsonObject);
        opportunityDao.jsonSetAndUpdateTime(corpid, id, map2, now);
        InsertDTO insertDTO = new InsertDTO();
        updateDataMap.put(FieldTypeEnum.UPDATETIME.getAlias(), now);
        insertDTO.setSource(updateDataMap);
        insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_OPPORTUNITY);
        insertDTO.setEsId(corpid+"_"+id);
        paasEsModel.update(insertDTO);
    }

    @Override
    public Long getMaxId(Map<String, Object> param) {
        return opportunityDao.getMaxId(param);
    }

    @Override
    public List<OpportunityEntityExt> getByKeysWithoutSub(Collection<Long> ids, String corpid) {
        Map<String,Object> map = new HashMap<>();
        map.put("corpid",corpid);
        map.put("idIn",ids);
        map.put("del",0);
        return opportunityDao.findEntitys(map);
    }
}
